'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const { 
    page = 1, 
    size = 20, 
    category_id, 
	 categoryId = '',
    keyword='', 
    orderBy = 'createTime',
    sortBy = 'create_date', 
    sortOrder = 'desc',
	  status=0
  } = event;
  
  try {
    // 构建查询条件
    let query = {
      status: 1 // 只返回已上架的壁纸
    };
    
    // 分类筛选
    if (categoryId && categoryId !== 'all') {
      query.categoryId = categoryId;
    }
    
    // 关键词搜索（标题或标签）
    if (keyword && keyword.trim()) {
      const keywordStr = keyword.trim();
      query = _.or([
        { title: db.RegExp({ regexp: keywordStr, options: 'i' }) },
        { tags: keywordStr }
      ]);
    }
    
    // 计算偏移量
    const skip = (page - 1) * size;
    
    // 构建排序
    const orderBy = {};
    orderBy[sortBy] = sortOrder === 'desc' ? -1 : 1;
    
    // 查询总数
    const countResult = await db.collection('wallpapers')
      .where(query)
      .count();
    
    // 查询列表
    const result = await db.collection('wallpapers')
      .where(query)
      .skip(skip)
      .limit(size)
      .orderBy(Object.keys(orderBy)[0], Object.values(orderBy)[0] === -1 ? 'desc' : 'asc')
      // .field({
      //   '_id': true,
      //   'title': true,
      //   'description': true,
      //   'category_id': true,
      //   'tags': true,
      //   'file_url': true,
      //   'thumbnail_url': true,
      //   'is_featured': true,
      //   'download_count': true,
      //   'favorite_count': true,
      //   'create_date': true
      // })
      .get();
    
    // 如果有用户ID，查询是否已收藏
    if (event.uniIdToken) {
      try {
        // 引入uni-id
        const { uniID } = require('uni-id-common');
        const uniIDIns = uniID.createInstance({ context });
        
        // 验证token获取用户信息
        const userInfo = await uniIDIns.checkToken(event.uniIdToken);
        if (userInfo.code === 0 && userInfo.uid) {
          const wallpaperIds = result.data.map(item => item._id);
          const favorites = await db.collection('favorites')
            .where({
              user_id: userInfo.uid,
              wallpaper_id: _.in(wallpaperIds)
            })
            .get();
          
          const favoriteMap = {};
          favorites.data.forEach(item => {
            favoriteMap[item.wallpaper_id] = true;
          });
          
          // 为壁纸列表添加是否已收藏的标记
          result.data = result.data.map(item => ({
            ...item,
            is_favorite: !!favoriteMap[item._id]
          }));
        }
      } catch (userError) {
        console.log('获取用户收藏状态失败:', userError);
        // 不影响主流程，继续返回壁纸列表
      }
    }
    
    return {
      code: 0,
      message: '获取壁纸列表成功',
      data: {
        list: result.data,
        total: countResult.total,
        page: page,
        size: size,
        hasMore: (page * size) < countResult.total
      },
      totalCount: countResult.total
    };
  } catch (error) {
    console.error('获取壁纸列表失败:', error);
    return {
      code: 500,
      message: '获取壁纸列表失败',
      error: error.message
    };
  }
};